package org.fglxy.mockserver.mock;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.fglxy.mockserver.entity.MockMessage;
import org.fglxy.mockserver.netty.NettyClient;
import org.fglxy.mockserver.netty.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;

public class ProxyClient implements IMockEnd {
	
	private static Logger LOGGER = LoggerFactory.getLogger(ProxyClient.class);
	
	private Channel channel;
	private NettyClient nettyClient;
	private String serverIp;
	private int serverPort;
	private String mockId;
	private ConcurrentLinkedQueue<MockMessage> queue = new ConcurrentLinkedQueue<>();
	
	public ProxyClient(String mockId, String serverIp, int serverPort, Channel channel) {
		this.mockId = mockId;
		this.serverIp = serverIp;
		this.serverPort = serverPort;
		this.channel = channel;
	}
	
	public void start() {
		this.nettyClient = new NettyClient(this.serverIp, this.serverPort);
		try {
			this.nettyClient.start(this);
			WebSocketServer.Instance.sendMsg(this.getMockId(), "代理服务启动:目标IP" + this.serverIp + ";目标端口:" + this.serverPort);
			LOGGER.info("proxy server start");
		} catch (InterruptedException e) {
		}
	}
	
	public void stop() {
		this.nettyClient.release();
		this.nettyClient.getChannel().close();
	}
	
	public void restart() {
		this.stop();
		this.start();
	}
	
	public void sendMsg(MockMessage msg) {
		if (this.nettyClient.getChannel().isActive()) {
			LOGGER.info("消息转发:cmdNo:{}", msg.getCmdNo());
			WebSocketServer.Instance.sendMsg(this.getMockId(), "消息转发:cmdNo:" + msg.getCmdNo());
			this.nettyClient.getChannel().writeAndFlush(msg);
		} else {
			this.queue.add(msg);
		}
	}

	@Override
	public void onConnectFinish(Channel channel) {
		this.nettyClient.release();
		LOGGER.info("代理服务与真实服务器连接断开");
		WebSocketServer.Instance.sendMsg(this.getMockId(), "代理服务与真实服务器连接断开");
		this.queue.clear();
	}

	@Override
	public void onReceive(Channel channel, MockMessage msg) {
		LOGGER.info("接收到真实服务器返回,转交客户端:cmdNo:{}", msg.getCmdNo());
		WebSocketServer.Instance.sendMsg(this.getMockId(), "接收到真实服务器返回,转交客户端:cmdNo:" + msg.getCmdNo());
		this.channel.writeAndFlush(msg);
	}

	@Override
	public void onConnect(Channel channel) {
		WebSocketServer.Instance.sendMsg(this.getMockId(), "代理服务与真实服务器连接成功");
		while (this.queue.size() > 0 && this.channel.isActive()) {
			this.sendMsg(this.queue.poll());
		}
	}

	@Override
	public String getMockId() {
		return this.mockId;
	}

	@Override
	public void init() {
		
	}

}
